import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# 加载数据集
diabetes = pd.read_csv('课程实训\diabetes.csv')
print("前10行数据:")
print(diabetes.head(10))

# 检查并处理异常值 - 将0值替换为列中位数
columns_to_replace = ['Glucose', 'BloodPressure', 'BMI', 'SkinThickness', 'Insulin']
for column in columns_to_replace:
    median = diabetes.loc[diabetes[column] != 0,column].median()
    diabetes.loc[diabetes[column] == 0,column] = median
# 计算糖尿病患者与非糖尿病患者的平均年龄差异
diabetic_mean_age = diabetes[diabetes['Outcome'] == 1]['Age'].mean()
non_diabetic_mean_age = diabetes[diabetes['Outcome'] == 0]['Age'].mean()
age_diff = diabetic_mean_age - non_diabetic_mean_age
print("糖尿病患者与非糖尿病患者的平均年龄差异: {:.2f}岁".format(age_diff))

# 创建2×2的子图布局
fig, axes = plt.subplots(2, 2, figsize=(14, 12))
fig.suptitle('糖尿病数据集关键指标可视化分析', fontsize=16)
plt.rcParams['font.sans-serif'] = ['SimHei']  # 设置 SimHei（黑体）
# 图形1: 糖尿病患者与非糖尿病患者的BMI分布箱线图
diabetic_bmi = diabetes[diabetes['Outcome'] == 1]['BMI']
non_diabetic_bmi = diabetes[diabetes['Outcome'] == 0]['BMI']

axes[0, 0].boxplot([non_diabetic_bmi, diabetic_bmi], 
                  labels=['非糖尿病', '糖尿病'],
                  patch_artist=True,
                  boxprops=dict(facecolor='lightblue'))
axes[0, 0].set_title('BMI分布箱线图')
axes[0, 0].set_ylabel('BMI指数')
axes[0, 0].set_xlabel('糖尿病状态')
axes[0, 0].grid(True, linestyle='--', alpha=0.7)

# 图形2: 年龄(Age)与血糖(Glucose)的散点图，按糖尿病结果着色
colors = ['green' if outcome == 0 else 'red' for outcome in diabetes['Outcome']]
axes[0, 1].scatter(diabetes['Age'], diabetes['Glucose'], c=colors, alpha=0.6)
axes[0, 1].set_title('年龄与血糖关系散点图')
axes[0, 1].set_xlabel('年龄(岁)')
axes[0, 1].set_ylabel('血糖浓度(mg/dL)')
# 创建自定义图例
from matplotlib.lines import Line2D
legend_elements = [Line2D([0], [0], marker='o', color='w', label='非糖尿病',
                          markerfacecolor='green', markersize=10),
                   Line2D([0], [0], marker='o', color='w', label='糖尿病',
                          markerfacecolor='red', markersize=10)]
axes[0, 1].legend(handles=legend_elements)
axes[0, 1].grid(True, linestyle='--', alpha=0.7)

# 图形3: BloodPressure的直方图（分糖尿病/非糖尿病双色）
axes[1, 0].hist([diabetes[diabetes['Outcome'] == 0]['BloodPressure'],
                diabetes[diabetes['Outcome'] == 1]['BloodPressure']],
                bins=15, color=['green', 'red'], 
                label=['非糖尿病', '糖尿病'], alpha=0.7)
axes[1, 0].set_title('血压分布直方图')
axes[1, 0].set_xlabel('血压(mm Hg)')
axes[1, 0].set_ylabel('频数')
axes[1, 0].legend()
axes[1, 0].grid(True, linestyle='--', alpha=0.7)

# 隐藏第四个图
axes[1, 1].axis('off')

# 调整布局
plt.tight_layout()
plt.subplots_adjust(top=0.9)
plt.show()